package com.mxpio.webapp.service.impl;

import com.mxpio.webapp.entity.MonitorTcp;
import com.mxpio.webapp.service.IMonitorTcpService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.initiator.JpaUtilAble;
import com.mxpioframework.jpa.query.Criteria;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: Cheng
 * @date: 2022/10/28
 */
@Service
public class MonitorTcpServiceImpl implements IMonitorTcpService, JpaUtilAble {
    @Override
    public void afterPropertiesSet(ApplicationContext applicationContext) {

    }

    @Override
    @Transactional(readOnly = false)
    public MonitorTcp create(MonitorTcp monitorTcp) {
        JpaUtil.save(monitorTcp);
        return monitorTcp;
    }

    @Override
    @Transactional(readOnly = false)
    public MonitorTcp update(MonitorTcp monitorTcp) {
        JpaUtil.update(monitorTcp);
        return monitorTcp;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<MonitorTcp> queryAll(Criteria criteria, Pageable pageable) {
        return JpaUtil.linq(MonitorTcp.class).where(criteria).paging(pageable);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(List<String> ids) {
        JpaUtil.lind(MonitorTcp.class).in("id", ids).delete();
    }

    @Override
    @Transactional(readOnly = false)
    public void editMonitorTcp(MonitorTcp monitorTcp) {
        //查询数据库中是否已经存在此目标主机和目标端口号的记录
        boolean exists = JpaUtil.linq(MonitorTcp.class)
                .equal("hostnameTarget", monitorTcp.getHostnameTarget())
                .equal("portTarget", monitorTcp.getPortTarget())
                .notEqual("id", monitorTcp.getId())
                .exists();
        if (exists) {
            throw new RuntimeException("重复的目标主机地址和目标端口号");
        }

        JpaUtil.update(monitorTcp);
    }

    @Override
    @Transactional(readOnly = true)
    public List<MonitorTcp> list() {
        return JpaUtil.linq(MonitorTcp.class).list();
    }
}
